package org.ehe.erp.service.product.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.ehe.common.core.enums.CommonStatusEnum;
import org.ehe.common.core.exception.BusinessException;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.erp.domain.product.ErpProduct;
import org.ehe.erp.domain.product.ErpProductUnit;
import org.ehe.erp.domain.product.bo.ErpProductUnitBo;
import org.ehe.erp.domain.product.vo.ErpProductUnitVo;
import org.ehe.erp.mapper.product.ErpProductUnitMapper;
import org.ehe.erp.service.product.IErpProductService;
import org.ehe.erp.service.product.IErpProductUnitService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 产品单位Service业务层处理
 *
 * @author zhangnn
 * @date 2024-04-30
 */
@RequiredArgsConstructor
@Service
public class ErpProductUnitServiceImpl extends ServiceImpl<ErpProductUnitMapper,ErpProductUnit> implements IErpProductUnitService {

    @Resource
    private final ErpProductUnitMapper baseMapper;
    private final IErpProductService productService;

    /**
     * 查询产品单位
     */
    @Override
    public ErpProductUnitVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询产品单位列表
     */
    @Override
    public TableDataInfo<ErpProductUnitVo> queryPageList(ErpProductUnitBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpProductUnit> lqw = buildQueryWrapper(bo);
        Page<ErpProductUnitVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询产品单位列表
     */
    @Override
    public List<ErpProductUnitVo> queryList(ErpProductUnitBo bo) {
        LambdaQueryWrapper<ErpProductUnit> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpProductUnit> buildQueryWrapper(ErpProductUnitBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpProductUnit> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), ErpProductUnit::getName, bo.getName());
        lqw.eq(bo.getStatus() != null, ErpProductUnit::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增产品单位
     */
    @Override
    public Boolean insertByBo(ErpProductUnitBo bo) {
        ErpProductUnit add = MapstructUtils.convert(bo, ErpProductUnit.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改产品单位
     */
    @Override
    public Boolean updateByBo(ErpProductUnitBo bo) {
        ErpProductUnit update = MapstructUtils.convert(bo, ErpProductUnit.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpProductUnit entity){
        ErpProductUnit existProductUnit = this.baseMapper.selectOne(new LambdaQueryWrapper<ErpProductUnit>()
            .eq(ErpProductUnit::getName, entity.getName()));

        if (Objects.isNull(existProductUnit)) {
            return;
        }

        // 情况2：存在同名记录 → 区分新增/修改
        Long entityId = entity.getId();
        // 新增场景：entity.getId() 为 null（未设置id），此时存在同名记录则报错
        if (Objects.isNull(entityId)) {
            throw new BusinessException("单位名称【" + entity.getName() + "】已存在，请更换名称");
        }

        // 修改场景：entity.getId() 不为 null，需判断同名记录是否为自身
        // 若存在的同名记录id与当前实体id不同 → 说明是其他记录，报错
        if (!existProductUnit.getId().equals(entityId)) {
            throw new BusinessException("单位名称【" + entity.getName() + "】已被其他记录占用，请更换名称");
        }

    }

    /**
     * 批量删除产品单位
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            List<ErpProduct> erpProducts = productService.getBaseMapper()
                .selectList(new LambdaQueryWrapper<ErpProduct>().in(ErpProduct::getUnitId, ids));
            if(erpProducts.size() > 0){
                throw new BusinessException("选择的[单位]中存在已被其他信息使用，禁止删除！");
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<ErpProductUnitVo> getProductUnitListByStatus() {
        return baseMapper.selectVoList(new LambdaQueryWrapper<ErpProductUnit>()
            .eq(ErpProductUnit::getStatus, CommonStatusEnum.ENABLE.getStatus()));
    }

    @Override
    public List<ErpProductUnitVo> getProductUnitList(Collection<Long> ids) {
        return baseMapper.selectVoBatchIds(ids);
    }
}
